package com.wetao.lib_common.player;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.ConcurrentHashMap;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;
import kotlin.jvm.internal.Intrinsics;

/**
 * author: zhouyh
 * created on: 2021/6/15 4:12 下午
 * description:
 */
public class RxBus {

    private static Subject mBus;
    private static ConcurrentHashMap mSubjects = new ConcurrentHashMap();
    @NotNull
    public static volatile RxBus instance;

    private RxBus() {
        mBus = PublishSubject.create().toSerialized();
    }

    public static RxBus getInstance(){
        if (instance == null){
            synchronized (RxBus.class){
                if (instance == null){
                    instance = new RxBus();
                }
            }
        }
        return instance;
    }


    public final void post(@NotNull Object o) {
        Intrinsics.checkNotNullParameter(o, "o");
        mBus.onNext(o);
    }

    private final Observable toObservable(Class eventType) {
        Observable observable = mBus.ofType(eventType);
        return observable;
    }

    private final Disposable doSubscribe(Class eventType, Consumer action) {
        Disposable disposable = this.toObservable(eventType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(action);
        return disposable;
    }

    private final void addDisposable(Object any, Disposable disposable) {
        String key = any.getClass().getName();
        if (mSubjects.get(key) != null) {
            CompositeDisposable compositeDisposable = (CompositeDisposable)mSubjects.get(key);
            if (compositeDisposable != null) {
                compositeDisposable.add(disposable);
            }
        } else {
            CompositeDisposable disposables = new CompositeDisposable();
            disposables.add(disposable);
            mSubjects.put(key, disposables);
        }

    }

    public final void register(@NotNull Object subscribe, @NotNull Class event, @NotNull Consumer action) {
        Disposable disposable = this.doSubscribe(event, action);
        this.addDisposable(subscribe, disposable);
    }

    public final void unRegister(@NotNull Object subscribe) {
        String key = subscribe.getClass().getName();
        if (mSubjects.containsKey(key) && mSubjects.get(key) != null) {
            CompositeDisposable var10000 = (CompositeDisposable)mSubjects.get(key);
            if (var10000 != null) {
                var10000.dispose();
            }
        }

        mSubjects.remove(key);
    }




}
